package cn.hamster3.mc.plugin.core.bukkit.util;

import lombok.Getter;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;

@SuppressWarnings("unused")
public class MinecraftVersion {
    @Getter
    public static final int Version1;
    @Getter
    public static final int Version2;
    @Getter
    public static final int Version3;

    static {
        String version = getMCVersion();
        String[] split = version.split("\\.");
        Version1 = Integer.parseInt(split[0]);
        Version2 = Integer.parseInt(split[1]);
        Version3 = split.length >= 3 ? Integer.parseInt(split[2]) : 0;
    }

    /**
     * 与当前服务端运行的 Minecraft 版本号对比
     * <p>
     * 1: 当前版本高于输入版本号
     * <p>
     * 2: 当前版本等于输入版本号
     * <p>
     * 2: 当前版本低于输入版本号
     *
     * @param version 比较的版本号
     * @return -
     */
    public static int compareTo(@NotNull String version) {
        String[] split = version.split("\\.");
        int version1 = Integer.parseInt(split[0]);
        int version2 = Integer.parseInt(split[1]);
        int version3 = split.length >= 3 ? Integer.parseInt(split[2]) : 0;
        int compare = Integer.compare(Version1, version1);
        if (compare != 0) {
            return compare;
        }
        compare = Integer.compare(Version2, version2);
        if (compare != 0) {
            return compare;
        }
        return Integer.compare(Version3, version3);
    }

    @NotNull
    public static String getMCVersion() {
        return Bukkit.getBukkitVersion().split("-")[0];
    }

    @NotNull
    public static String getNMSVersion() {
        return Bukkit.getServer().getClass().getName().split("\\.")[3];
    }

    @NotNull
    public static Class<?> getNMSClass(@NotNull String className) throws ClassNotFoundException {
        if (Version2 >= 17) {
            return Class.forName("net.minecraft.server." + className);
        }
        String nmsVersion = getNMSVersion();
        return Class.forName("net.minecraft.server." + nmsVersion + "." + className);
    }

    @NotNull
    public static Class<?> getNMSClassSilent(@NotNull String className) {
        String nmsVersion = getNMSVersion();
        try {
            return Class.forName("net.minecraft.server." + nmsVersion + "." + className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @NotNull
    public static Class<?> getCraftBukkitClass(@NotNull String className) throws ClassNotFoundException {
        String nmsVersion = getNMSVersion();
        return Class.forName("org.bukkit.craftbukkit." + nmsVersion + "." + className);
    }

    @NotNull
    public static Class<?> getCraftBukkitClassSilent(@NotNull String className) {
        String nmsVersion = getNMSVersion();
        try {
            return Class.forName("org.bukkit.craftbukkit." + nmsVersion + "." + className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
